package com.jx.driving.protocol.terminal.codec;

import java.lang.reflect.Field;

/**
 * 属性读取写入抽象类
 * 
 * @author shenliuyang
 *
 *         2016年7月29日下午6:22:27
 */
public abstract class FieldReaderWriter implements FieldReader, FieldWriter, Comparable<FieldReaderWriter> {

    protected Field field;
    protected int size;
    protected int order;

    public FieldReaderWriter(Field field, int size, int order) {
	super();
	this.field = field;
	this.size = size;
	this.order = order;
	field.setAccessible(true);
    }

    protected Object readFromField(Object obj) {
	try {
	    return field.get(obj);
	} catch (IllegalArgumentException | IllegalAccessException e) {
	    throw new RuntimeException(e);
	}
    }

    protected void wrtietoField(Object obj, Object data) {
	try {
	    field.set(obj, data);
	} catch (IllegalArgumentException | IllegalAccessException e) {
	    throw new RuntimeException(e);
	}
    }

    @Override
    public int compareTo(FieldReaderWriter o) {
	return Integer.valueOf(order).compareTo(o.order);
    }

}